//
//  MM_Custom_MutiTabMenuView.m
//  MallManage_IOS
//
//  Created by 张浩 on 2023/9/20.
//

#import "MM_Custom_MutiTabMenuView.h"

static const NSInteger kAddNameTag = 1000;
static const NSInteger KAddRedMessageTag = 100;

@interface MM_Custom_MutiTabMenuView ()

@property (nonatomic,strong) UIView * lineView;

@property (nonatomic,strong) UIScrollView * baseScrollView;
/**  上部线  */
@property (nonatomic, strong) UIView * topLineView;
/**  底部线  */
@property (nonatomic, strong) UIView * bottomLineView;
/**  index  */
@property (nonatomic, assign) NSInteger index;

@end

@implementation MM_Custom_MutiTabMenuView

#pragma mark - 生命周期

- (instancetype)init
{
    self = [super init];
    if (self) {
        _is_Left = NO;
        _is_Change = NO;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];
  if (self) {
    self.backgroundColor = [UIColor whiteColor];
//    self.selectedColor = [UIColor blueColor];
      self.selectedColor = [ColorUtil colorWithHexadecimal:@"#1F71C4"];
//      self.selectedFont = FONT(RATIO(40));
      self.selectedFont = FONT_BOLD(18);
      self.normalFont = FONT(18);
      self.normalColor = [ColorUtil colorWithHexadecimal:@"#333333"];
      self.isHiddenLineView = YES;
//    self.normalColor   = [UIColor blackColor];
      self.lineView_h = 3;
    self.sameDivide = YES;
    self.noDivideSpace = 60;
    [self addSubview:self.baseScrollView];
    
    [self.baseScrollView addSubview:self.lineView];
    [self addSubview:self.bottomLineView];
    [self addSubview:self.topLineView];
  }
  return self;
}
- (void)dealloc {
  
}
#pragma mark - 私有方法
- (void)tapClick:(UITapGestureRecognizer *)tap {
  
  NSInteger index = tap.view.tag -kAddNameTag;
    
    if (!self.is_Change) {
        [self setupSelectedIndex:index];
    }
  
  if ([self.delegate respondsToSelector:@selector(mutiTabView:sectionViewSelectedIndex:)]) {
    [self.delegate mutiTabView:self sectionViewSelectedIndex:index];
  }
  
}

/* 滑动到 某个地方 **/
- (void)setupSelectedIndex:(NSInteger)index {
  
    _index = index;
  for (UILabel * label in self.baseScrollView.subviews) {
    if ([label isKindOfClass:[UILabel class]]) {
      
      if (label.tag >= kAddNameTag) {
        
        if (label.tag == index+kAddNameTag) {
          label.textColor = self.selectedColor;
            label.font = self.selectedFont;
          [self lineViewScrollToIndex:index];
        }else {
          label.textColor = self.normalColor;
            label.font = self.normalFont;
        }
      }
      
    }
  }
}

//获取当前位置
- (NSInteger)getSelectedIndex{
    return _index;
}
/* 底部的线 滑动到 某个地方 **/
- (void)lineViewScrollToIndex:(NSInteger)index {
  
  [UIView animateWithDuration:0.3 animations:^{
    
    [self setLineViewFrameWithIndex:index];
    //self.lineView.x = index*self.lineView.width;
    
  }completion:^(BOOL finished) {
    
    CGPoint point = self.baseScrollView.contentOffset;
    CGPoint lineViewToSelfPoint = [self.lineView.superview convertPoint:self.lineView.center toView:self];
    //把当前的滑动到中心点的距离
    CGFloat toScrollViewCenter = lineViewToSelfPoint.x - self.center.x;
    if (toScrollViewCenter <0) {//要向右边滑动contentOffset.x >=0
      // 这里表示scrollView向右滑动
      point.x += toScrollViewCenter;
      // 但是向右滑动不能小于0，否则将会出现第一个 也向右偏移
      if (point.x <0) {
        point.x = 0;
      }
    }else {//向左滑动 contentOffset.x <= relationValue
      //这里表示向左滑动
      //这个是最大的偏移X量
      
      CGFloat maxOffX = self.baseScrollView.contentSize.width - self.baseScrollView.MM_w;
      
      if (maxOffX > 0) {
        point.x += toScrollViewCenter;
        // 如果向左滑动超出了它的最大偏移量
        if (point.x>maxOffX) {
          point.x = maxOffX;
        }
      }
      
      
    }
    [self.baseScrollView setContentOffset:point animated:YES];
  }];
  
}

- (void)setSelectedColor:(UIColor *)selectedColor {
    _selectedColor = selectedColor;
    
    self.lineView.backgroundColor = selectedColor;
}

- (void)setIsHiddenLineView:(BOOL)isHiddenLineView {
    _isHiddenLineView = isHiddenLineView;
    
    self.topLineView.hidden = isHiddenLineView;
    self.bottomLineView.hidden = isHiddenLineView;
}

- (void)setCurrentHiddenLine:(BOOL)currentHiddenLine {
    _currentHiddenLine = currentHiddenLine;
    
    self.lineView.hidden = currentHiddenLine;
}

#pragma mark - get 方法

- (UIScrollView *)baseScrollView {
  
  if (_baseScrollView == nil) {
    
    _baseScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width, self.bounds.size.height - RATIO(1))];
    _baseScrollView.showsHorizontalScrollIndicator = NO;
    _baseScrollView.showsVerticalScrollIndicator = NO;
    
  }
  return _baseScrollView;
  
}

- (UIView *)lineView {
  
  if (_lineView == nil) {
    _lineView = [[UIView alloc]init];
      _lineView.layer.cornerRadius = 3;
      _lineView.clipsToBounds = YES;
    _lineView.backgroundColor = self.selectedColor;
  }
  return _lineView;
}

- (UIView *)bottomLineView{
  if (!_bottomLineView) {
    _bottomLineView = [[UIView alloc]initWithFrame:CGRectMake(self.baseScrollView.MM_x, self.baseScrollView.MM_y, self.baseScrollView.MM_w, RATIO(1))];
    _bottomLineView.backgroundColor = [UIColor grayColor];
  }
  return _bottomLineView;
}

- (UIView *)topLineView{
  if (!_topLineView) {
    _topLineView = [[UIView alloc]initWithFrame:CGRectMake(self.baseScrollView.MM_x, self.baseScrollView.MM_h - RATIO(1), self.baseScrollView.MM_w, RATIO(1))];
    _topLineView.backgroundColor = [UIColor grayColor];
  }
  return _topLineView;
}

/* 根据 字的大小 来显示 lineView的宽度 **/
- (void)setLineViewFrameWithIndex:(NSInteger)index {
  
  UILabel * label = [self.baseScrollView viewWithTag:kAddNameTag+index];
    
    if (self.lineViewSameH > 0) {
        self.lineView.MM_w = self.lineViewSameH;
        self.lineView.MM_Center_X = label.MM_Center_X;
        return;
    } else {
        if (self.lineViewSameW) {
            
            self.lineView.MM_w = self.MM_w / _titleArr.count;
            self.lineView.MM_Center_X = label.MM_Center_X;
            return;
        }
    }
  
  NSString * text = label.text;
  
    CGSize textSize = [Custom_ZHTool getTextSizeWithFont:label.font text:text];
    
//  CGSize textSize = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
//                                       options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
//                                    attributes:@{NSFontAttributeName:label.font}
//                                       context:nil].size;
  self.lineView.MM_w = textSize.width;
    
    if (self.is_Left) {
        self.lineView.MM_x = label.MM_x - RATIO(20);
    }else {
        self.lineView.MM_Center_X = label.MM_Center_X;
    }
  
}



#pragma mark - 公共方法
- (void)setTitleArr:(NSArray *)items {
  
  if (items.count<=0) {
    return;
  }
  
  _titleArr = items;
  CGFloat lineH = 2;
  CGFloat baseLineH = 1;
  
  CGFloat itemLeft = 12;
  CGFloat itemW = 0;
  
  
  
  CGFloat itemH = self.frame.size.height - lineH - baseLineH;
  
  for (UIView *subViews in self.baseScrollView.subviews) {
    
    if ([subViews isKindOfClass:[UILabel class]]) {
      subViews.hidden = YES;
    }
  }
  
  for (NSInteger i = 0; i<items.count; i++) {
    
    UILabel * nameLabel = [self.baseScrollView viewWithTag:i+kAddNameTag];
    
    if (nameLabel == nil) {
      nameLabel = [[UILabel alloc] init];
      nameLabel.userInteractionEnabled = YES;
      nameLabel.tag  = i+kAddNameTag;
        nameLabel.font = self.normalFont;
      UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick:)];
      [nameLabel addGestureRecognizer:tap];
      [self.baseScrollView addSubview:nameLabel];
      if (i == 0) {//默认第一个
        nameLabel.textColor = self.selectedColor;
      }else {
        nameLabel.textColor = self.normalColor;
      }
      
    }else {
      nameLabel.hidden = NO;
    }
      
      if (self.is_Left) {
          nameLabel.textAlignment = NSTextAlignmentLeft;
      }else {
          nameLabel.textAlignment = NSTextAlignmentCenter;
      }
    nameLabel.text = items[i];
    CGSize nameSize = [Custom_ZHTool getTextSizeWithFont:nameLabel.font text:nameLabel.text];
    
    if (self.sameDivide) {
      NSInteger tempCount = items.count>=5?5:items.count;
      itemW = self.MM_w/tempCount;
      itemLeft = i*itemW;
    }else{
      itemW = nameSize.width + self.noDivideSpace;
    }
    
      nameLabel.frame = CGRectMake(self.is_Left?12:itemLeft, 0, itemW, itemH);
//    [nameLabel makeConstraints:^(MASConstraintMaker *make) {
//      make.left.equalTo(itemLeft);
//      make.width.equalTo(itemW);
//      make.height.equalTo(itemH);
//      make.top.equalTo(0);
//    }];
    
    if (!self.sameDivide) {
      itemLeft += nameSize.width + self.noDivideSpace;
    }
    
      //默认选中0
      [self setupSelectedIndex:0];
    /* 红色的提醒**/
    CGFloat messageLabelRadius = RATIO(40);
    UILabel * messageLabel = [[UILabel alloc] init];
    [messageLabel setBackgroundColor:[UIColor redColor]];
    [messageLabel setTextColor:[UIColor whiteColor]];
    [messageLabel setTextAlignment:NSTextAlignmentCenter];
    [messageLabel setFont:[UIFont systemFontOfSize:10.f]];
    [messageLabel.layer setMasksToBounds:YES];
    messageLabel.layer.cornerRadius = messageLabelRadius;
    messageLabel.hidden = YES;
    messageLabel.tag = i + KAddRedMessageTag;
    
    [self.baseScrollView addSubview:messageLabel];
    [messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
      make.centerY.equalTo(-5);
      make.left.equalTo(nameLabel.mas_right).offset(-(nameLabel.MM_w-nameSize.width)/2-5);
      make.width.with.height.mas_equalTo(10);
    }];
  }
  
  self.lineView.MM_y = itemH;
    if (self.lineView_h > 0) {
        self.lineView.MM_h = self.lineView_h;
    } else {
        self.lineView.MM_h = lineH;
    }
  [self setLineViewFrameWithIndex:0];
  
  CGFloat contentW = 0;
  if (self.sameDivide) {
    contentW = items.count*itemW;
  }else{
    contentW = itemLeft;
  }
  
  self.baseScrollView.contentSize = CGSizeMake(contentW, 0);
}

/* 设置某个位置的未读数  **/
- (void)setupMessageRedCount:(NSInteger)redCount
                   withIndex:(NSInteger)index {
  
  UILabel * messageLabel = [self.baseScrollView viewWithTag:index + KAddRedMessageTag];
  if (redCount>0) {
    
    messageLabel.hidden = NO;
    NSString * redMessage = redCount >= 100 ?@"99+":@(redCount).description;
    messageLabel.text = redMessage;
    CGSize redMessageSize = [Custom_ZHTool getTextSizeWithFont:messageLabel.font text:messageLabel.text maxWidth:10000];
    
    CGFloat redMessageLabelH = redMessageSize.height+ 2;
    CGFloat redMessageLabelW = MAX(redMessageSize.width + 2, redMessageLabelH);
    messageLabel.layer.cornerRadius = redMessageLabelH/2.0;
    
    [messageLabel mas_updateConstraints:^(MASConstraintMaker *make) {
      make.width.equalTo(redMessageLabelW);
      make.height.equalTo(redMessageLabelH);
    }];
    
  }else {
    messageLabel.hidden = YES;
  }
}

/** 设置某个位置是否显示小红点标记 **/
- (void)setupRedSign:(BOOL)isShow withIndex:(NSInteger)index {
    UILabel * messageLabel = [self.baseScrollView viewWithTag:index + KAddRedMessageTag];
    
    if (isShow) {
        messageLabel.hidden = NO;
        CGFloat redMessageLabelH = RATIO(12);
        CGFloat redMessageLabelW = RATIO(12);
        messageLabel.layer.cornerRadius = redMessageLabelH/2.0;
        UILabel * nameLabel = [self.baseScrollView viewWithTag:index+kAddNameTag];
        CGSize  nameSize = [Custom_ZHTool getTextSizeWithFont:nameLabel.font text:nameLabel.text];

        [messageLabel remakeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(-5);
            make.left.equalTo(nameLabel.right).offset(-(nameLabel.MM_w-nameSize.width)/2);
            make.width.equalTo(redMessageLabelW);
            make.height.equalTo(redMessageLabelH);
        }];

    }else {
        messageLabel.hidden = YES;
    }
}

/**
 设置总数
 
 @param totalCount 总数
 @param index 第几个
 */
- (void)setupTotalCount:(NSInteger)totalCount withIndex:(NSInteger)index {
//    _index = index;
    
  UILabel * nameLabel = [self.baseScrollView viewWithTag:index + kAddNameTag];
  
  NSString * title = self.titleArr[index];

  NSString * redMessage = totalCount >= 100 ?@"99+":@(totalCount).description;
//  if (totalCount > 0) {
    NSString * keyStr = [NSString stringWithFormat:@"(%@)",redMessage];
  
  NSString * allStr = [NSString stringWithFormat:@"%@%@",title,keyStr];
    
    NSMutableAttributedString * att = [[NSMutableAttributedString alloc]initWithString:allStr];
    
    [att addFontAttributeWithFont:FONT(RATIO(24)) partStr:keyStr allStr:allStr isRecursive:NO];
    
    nameLabel.attributedText = att;
//  }else{
//    nameLabel.text = title;
//  }
}
@end
